<template>
    <div class="tag-management-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>小红书标签管理</span>
            <el-button type="primary" @click="handleAdd">新增标签</el-button>
          </div>
        </template>
  
        <!-- 查询表单 -->
        <el-form :model="queryForm" inline>
          <el-form-item label="标签名称">
            <el-input v-model="queryForm.tagname" placeholder="请输入标签名称" clearable />
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="queryForm.categoryname" placeholder="请选择分类" clearable>
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
              <el-option label="正常" :value="1" />
              <el-option label="待审核" :value="2" />
              <el-option label="禁用" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
  
        <!-- 数据表格 -->
        <el-table
          :data="tableData"
          v-loading="loading"
          border
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="tagname" label="标签名称" min-width="120" />
          <el-table-column prop="categoryname" label="分类" width="120" />
          <el-table-column prop="tagdesc" label="描述" min-width="180" show-overflow-tooltip />
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="statusType[row.status]">
                {{ statusText[row.status] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="usecount" label="使用数" width="90" />
          <el-table-column prop="followcount" label="关注数" width="90" />
          <el-table-column label="是否推荐" width="100">
            <template #default="{ row }">
              <el-tag :type="row.isrecommend ? 'success' : 'info'">
                {{ row.isrecommend ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatTime(row.createtime) }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template #default="{ row }">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 新增/编辑弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        @closed="resetForm"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="标签名称" prop="tagname">
            <el-input v-model="formData.tagname" placeholder="请输入标签名称" />
          </el-form-item>
          <el-form-item label="标签别名" prop="tagalias">
            <el-select
              v-model="formData.tagsalias"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请输入标签别名"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="标签描述" prop="tagdesc">
            <el-input
              v-model="formData.tagdesc"
              type="textarea"
              :rows="3"
              placeholder="请输入标签描述"
            />
          </el-form-item>
          <el-form-item label="分类" prop="categoryname">
            <el-select
              v-model="formData.categoryname"
              placeholder="请选择分类"
              style="width: 100%"
            >
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="2">待审核</el-radio>
              <el-radio :label="3">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否推荐">
            <el-switch v-model="formData.isrecommend" />
          </el-form-item>
          <el-form-item label="是否敏感">
            <el-switch v-model="formData.issensitive" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import request from '../utils/request'
  
  // 状态映射
  const statusText = {
    1: '正常',
    2: '待审核',
    3: '禁用'
  }
  
  const statusType = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  
  // 查询表单
  const queryForm = reactive({
    tagname: '',
    categoryname: null,
    status: null,
    pageNum: 1,
    pageSize: 10
  })
  
  // 表格数据
  const tableData = ref([])
  const total = ref(0)
  const loading = ref(false)
  
  // 分类选项 (模拟数据，实际应从接口获取)
  const categoryOptions = ref([
    { value: '美妆', label: '美妆' },
    { value: '穿搭', label: '穿搭' },
    { value: '美食', label: '美食' },
    { value: '旅行', label: '旅行' },
    { value: '家居', label: '家居' }
  ])
  
  // 弹窗相关
  const dialogVisible = ref(false)
  const dialogTitle = ref('新增标签')
  const formRef = ref(null)
  const formData = reactive({
    id: null,
    tagname: '',
    tagsalias: [],
    tagdesc: '',
    categoryname: null,
    categoryname: '',
    status: 1,
    isrecommend: false,
    issensitive: false
  })
  
  // 表单验证规则
  const rules = {
    tagname: [
      { required: true, message: '请输入标签名称', trigger: 'blur' },
      { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    categoryname: [
      { required: true, message: '请选择分类', trigger: 'change' }
    ]
  }
  
  // 获取标签列表
  const getTagList = async () => {
    try {
      loading.value = true
      const res = await request.post('/xhs/tag/getTagsPage', queryForm)
      debugger;
      tableData.value = res.data.records || []
      total.value = res.data.total || 0
    } catch (error) {
      console.error('获取标签列表失败:', error)
      ElMessage.error('获取标签列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 查询
  const handleQuery = () => {
    queryForm.pageNum = 1
    getTagList()
  }
  
  // 重置查询
  const resetQuery = () => {
    Object.assign(queryForm, {
      tagname: '',
      categoryname: null,
      status: null,
      pageNum: 1,
      pageSize: 10
    })
    handleQuery()
  }
  
  // 分页大小变化
  const handleSizeChange = (val) => {
    queryForm.pageSize = val
    getTagList()
  }
  
  // 当前页变化
  const handleCurrentChange = (val) => {
    queryForm.pageNum = val
    getTagList()
  }
  
  // 新增标签
  const handleAdd = () => {
    dialogTitle.value = '新增标签'
    dialogVisible.value = true
  }
  
  // 编辑标签
  const handleEdit = (row) => {
    dialogTitle.value = '编辑标签'
    Object.assign(formData, {
      id: row.id,
      tagname: row.tagname,
      tagsalias: row.tagsalias || [],
      tagdesc: row.tagdesc || '',
      categoryname: row.categoryname,
      categoryname: row.categoryname,
      status: row.status,
      isrecommend: row.isrecommend || false,
      issensitive: row.issensitive || false
    })
    dialogVisible.value = true
  }
  
  // 删除标签
  const handleDelete = (row) => {
    ElMessageBox.confirm(`确定删除标签 "${row.tagname}" 吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await request.post('/xhs/tag/deleteTagById', { id: row.id })
        ElMessage.success('删除成功')
        getTagList()
      } catch (error) {
        console.error('删除标签失败:', error)
        ElMessage.error('删除标签失败')
      }
    }).catch(() => {})
  }
  
  // 提交表单
  const submitForm = async () => {
    try {
      await formRef.value.validate()
      
      const apiUrl = formData.id ? '/xhs/tag/updateTag' : '/xhs/tag/addTag'
      const successMsg = formData.id ? '更新成功' : '新增成功'
      
      const payload = {
        ...formData,
        // 处理JSON字段
        tagalias: JSON.stringify(formData.tagsalias),
        relatedtags: '[]',
        extradata: '{}'
      }
      
      await request.post(apiUrl, payload)
      ElMessage.success(successMsg)
      dialogVisible.value = false
      getTagList()
    } catch (error) {
      console.error('表单提交失败:', error)
      if (error.name !== 'ValidateError') {
        ElMessage.error(error.message || '操作失败')
      }
    }
  }
  
  // 重置表单
  const resetForm = () => {
    formRef.value?.resetFields()
    Object.assign(formData, {
      id: null,
      tagname: '',
      tagsalias: [],
      tagdesc: '',
      categoryname: null,
      categoryname: '',
      status: 1,
      isrecommend: false,
      issensitive: false
    })
  }
  
  // 格式化时间
  const formatTime = (time) => {
    if (!time) return ''
    return new Date(time).toLocaleString()
  }
  
  // 初始化加载数据
  onMounted(() => {
    getTagList()
  })
  </script>
  
  <style scoped>
  .tag-management-container {
    padding: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  </style>